﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;

using mshtml;

namespace WebBrowserTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Image GetImage()
        {
            HTMLDocument html = (HTMLDocument)this.webBrowser1.Document.DomDocument;
            IHTMLControlElement img = (IHTMLControlElement)webBrowser1.Document.Images["vfcode"].DomElement;

            IHTMLControlRange range = (IHTMLControlRange)((HTMLBody)html.body).createControlRange();
            range.add(img);
            range.execCommand("Copy", false, null);
            img = null;
            range = null;
            html = null;

            Image image = null;
            if (Clipboard.ContainsImage())
            {
                image = Clipboard.GetImage();

            }
            Clipboard.Clear();

            return image;
        }

        private string GetHtml()
        {
            Encoding enc = Encoding.GetEncoding(webBrowser1.Document.Encoding);
            System.IO.StreamReader stream = new System.IO.StreamReader(webBrowser1.DocumentStream, enc);
            return stream.ReadToEnd();
        }

        private void callJsMethod(string jsfun, params object[] jsParameter)//函数名字,函数参数
        {
            HtmlDocument doc = webBrowser1.Document;
            doc.InvokeScript(jsfun, jsParameter);
        }

        private void ClickByID(string htmlElementID)
        {
            HtmlElementCollection hec = webBrowser1.Document.All;
            for (int i = 0; i < hec.Count; i++)
            {
                if (hec[i].GetAttribute("id").Equals(htmlElementID))
                {
                    hec[i].InvokeMember("click");
                }
            }
        }

        private object GetVariable(string VariableName)
        {
            IHTMLDocument2 vDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;
            IHTMLWindow2 vWindow = (IHTMLWindow2)vDocument.parentWindow;
            Type vWindowType = vWindow.GetType();
            object o = vWindowType.InvokeMember(VariableName, System.Reflection.BindingFlags.GetProperty, null, vWindow, new object[] { }); // 读取
            return o;
        }

        private void DelayTimes(int seconds)
        {
            int i = 0;
            do
            {
                System.Threading.Thread.Sleep(1);
                Application.DoEvents();
                i += 1;
            } while (i < seconds * 1000);
        }

        private string GetPage(string url)
        {
            CookieContainer myCookieContainer = new CookieContainer();

            string cookieStr = webBrowser1.Document.Cookie;
            string[] cookStr = cookieStr.Split(';');
            foreach (string str in cookStr)
            {
                string[] cookieNameValue = str.Split('=');
                Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString().Replace(",", ""));
                ck.Domain = "qq.com";
                myCookieContainer.Add(ck);
            }

            HttpWebRequest hreq = (HttpWebRequest)HttpWebRequest.Create(url);
            hreq.AllowAutoRedirect = true;
            hreq.KeepAlive = true;
            hreq.Method = "GET";
            hreq.ContentType = "application/x-www-form-urlencoded";
            hreq.CookieContainer = myCookieContainer;
            hreq.Headers["Cookie"] = webBrowser1.Document.Cookie;
            //hreq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";

            HttpWebResponse response = (HttpWebResponse)hreq.GetResponse();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
            {
                return sr.ReadToEnd();
            }
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url == webBrowser1.Document.Url)
            {
                //MessageBox.Show("頁面加載完成！", "DocumentCompleted");
                //DelayTimes(1);
                webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted;

                timer1.Interval = 1000;
                timer1.Enabled = true;
            }
        }

        private void webBrowser1_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
            progressBarX1.Visible = true;

            if (e.CurrentProgress > 0 && e.MaximumProgress > 0)
            {
                progressBarX1.Maximum = Convert.ToInt32(e.CurrentProgress);
                progressBarX1.Step = Convert.ToInt32(e.CurrentProgress);
                progressBarX1.PerformStep();
            }
            else if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                progressBarX1.Value = 0;
                progressBarX1.Visible = false;
            }
        }

        //////////////////////////////////////////////////////////////////////////

        private void btn_EmailOpen_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://mail.qq.com/cgi-bin/loginpage?");

            while (webBrowser1.ReadyState < WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
        }

        private void btn_EmailGetVerify_Click(object sender, EventArgs e)
        {
            
            callJsMethod("showVerify", "true");//顯示驗證碼
            picVerify.Image = GetImage();
        }

        private void btn_EmailFillin_Click(object sender, EventArgs e)
        {
            webBrowser1.Document.GetElementById("uin").InnerText = this.txtAccount.Text.Trim();
            webBrowser1.Document.GetElementById("pp").InnerText = this.txtPassword.Text.Trim();
            webBrowser1.Document.GetElementById("verifycode").InnerText = this.txtVerify.Text.Trim();
        }

        private void btn_EmailLogin_Click(object sender, EventArgs e)
        {
            ClickByID("btlogin");//模擬點擊登錄按鈕

            webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
        }

        //////////////////////////////////////////////////////////////////////////
       
        private void btn_GroupOpen_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://ui.ptlogin2.qq.com/cgi-bin/login?appid=3000801&s_url=http%3A%2F%2Fqun.qq.com%2Fair%2F&f_url=loginerroralert&lang=2052&bgcolor=ffffff&style=1&low_login=1&link_target=blank&target=top&hide_title_bar=1&dummy=1");
            while (webBrowser1.ReadyState < WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
        }

        private void btn_GroupSwitch_Click(object sender, EventArgs e)
        {
            object ShowQuickLogin = GetVariable("curXui");
            bool Show = Convert.ToBoolean(ShowQuickLogin.ToString());
            if (Show)
            {//如果顯示了快速登錄，則需要切換一下界面
                callJsMethod("switchpage");
            }
        }

        private void btn_GroupFillin_Click(object sender, EventArgs e)
        {
            webBrowser1.Document.GetElementById("u").InnerText = this.txtAccount2.Text.Trim();
            webBrowser1.Document.GetElementById("p").InnerText = this.txtPassword2.Text.Trim();
        }

        private void btn_GroupLogin_Click(object sender, EventArgs e)
        {
            ClickByID("login_button");//模擬登錄

            webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
        }

        private void btnQuickLogin_Click(object sender, EventArgs e)
        {
            btn_GroupOpen_Click(sender, e);
            btn_GroupSwitch_Click(sender, e);
            btn_GroupFillin_Click(sender, e);
            DelayTimes(1);//延遲1秒後登錄，避免輸入驗證碼(TX真賤)
            btn_GroupLogin_Click(sender, e);           

            DelayTimes(1);

            HtmlElement errm = webBrowser1.Document.GetElementById("err_m");
            string str = errm != null ? errm.InnerHtml : "";
            if (!string.IsNullOrEmpty(str) && !str.Equals(""))
            {
                webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted;

                //说明登录失败
                MessageBox.Show("登录失败");
            }
        }        

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            string tttt = webBrowser1.Document.GetElementById("trUserStatus").InnerHtml;

            webBrowser1.Navigate("http://qun.qq.com/air/4610534/addr/index/type/1/p/1?w=n");
            while (webBrowser1.ReadyState < WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }

            string sss = GetHtml();

            //webBrowser1.DocumentCompleted += Test;
        } 
    }
}